package net.linku.filter;

import net.linku.constant.TraceConstants;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 请求结束后清除 traceId 的过滤器。
 */
public class TraceIdFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化方法，可以为空实现
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String traceId = httpRequest.getHeader(TraceConstants.TRACE_ID); // 从请求头获取 traceId
        try {
            if (traceId != null && !traceId.isEmpty()) {
                MDC.put(TraceConstants.TRACE_ID, traceId); // 设置 traceId 到 MDC
            }
            chain.doFilter(request, response);
        } finally {
            MDC.remove(TraceConstants.TRACE_ID); // 清除 traceId
        }
    }

    @Override
    public void destroy() {
        // 销毁方法，可以为空实现
    }
}
